package com.liu.controller;

import com.alibaba.fastjson.JSONObject;
import com.liu.api.pojo.Users;
import com.liu.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/provider/users/")
public class UsersControllor {
    @Autowired
    private UsersService usersService;

    @RequestMapping(value = "addUsers", method = RequestMethod.POST)
    public void addUsers(@RequestBody JSONObject param) {
        List<Users> usersLs = (List<Users>) param.get("USERS_LIST");
        usersService.addUsers(usersLs);
    }

    @RequestMapping(value = "delUsers", method = RequestMethod.DELETE)
    public void delUsers(@RequestParam(value = "userId") String userId) {
        usersService.delUsers(userId);
    }

    @RequestMapping(value = "modifyUsers", method = RequestMethod.PUT)
    public void modifyUsers(@RequestBody JSONObject param) {
        Users users = new Users();
        users.init(param.getJSONObject("USERS"));
        usersService.modifyUsers(users);
    }

    @RequestMapping(value = "queryUsersCount", method = RequestMethod.GET)
    public JSONObject queryUsersCount(@RequestParam(value = "usersString") String usersString) {
        JSONObject result = new JSONObject();
        JSONObject json = JSONObject.parseObject(URLDecoder.decode(usersString));
        Users users = new Users();
        users.init(json.getJSONObject("USERS"));
        int count = usersService.queryUsersCount(users);
        result.put("COUNT", count);
        return result;
    }

    @RequestMapping(value = "queryUsers", method = RequestMethod.GET)
    public JSONObject queryUsers(@RequestParam(value = "usersString") String usersString) {
        JSONObject result = new JSONObject();
        JSONObject json = JSONObject.parseObject(URLDecoder.decode(usersString));
        Users users = new Users();
        users.init(json.getJSONObject("USERS"));
        int count = usersService.queryUsersCount(users);
        List<Users> usersList = new ArrayList<>();
        if (count > 0) {
            usersList = usersService.queryUsers(users);
        }
        result.put("COUNT", count);
        result.put("USERS_LIST", usersList);
        return result;
    }
}
